//
//  NSString+BZEncrypt.m
//  BZFoundation
//
//  Created by 郭艺伟 on 2017/10/1.
//  Copyright © 2017年 郭艺伟. All rights reserved.
//

#import "NSString+BZEncrypt.h"
#import <CommonCrypto/CommonDigest.h>

/**
 *    从一个NSString对象中生成一个MD5过后的字符串
 *
 *    @param string  需要MD5的字符串
 *    @param isShort 是否短MD5（16字符-true 32字符-false）
 *
 *    @return 经过MD5后的字符串
 */
NSString *bz_MD5(NSString *string, bool isShort) {
    if (!string || [string length] == 0) {
        return nil;
    }
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *output = nil;
    if (isShort) {
        output = [NSMutableString stringWithFormat:
                  @"%02x%02x%02x%02x%02x%02x%02x%02x",
                  digest[4], digest[5], digest[6], digest[7],
                  digest[8], digest[9], digest[10], digest[11]
                  ];
        
    } else {
        output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
        
        for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
            [output appendFormat:@"%02x", digest[i]];
        }
    }
    
    return output;
}


@implementation NSString (BZEncrypt)
- (NSString *)bz_md5String32 {
    return bz_MD5(self, false);
}

- (NSString *)bz_md5String16 {
    return bz_MD5(self, true);
}
@end
